<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>店铺页面 - 酒店管理系统</title>
    <link href="https://cdn.tailwindcss.com" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
        }
        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.4);
        }
        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 30%;
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }
        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">

<!-- 页面顶部 -->
<div class="flex justify-between items-center bg-white shadow px-6 py-4 mb-6">
    <h1 class="text-2xl font-bold text-gray-800">店铺页面</h1>
    <div class="text-sm text-gray-600">
        当前用户：
        <span id="loggedInUser" class="font-semibold text-indigo-600"></span>
    </div>
</div>

<!-- 主体内容 -->
<div class="container mx-auto px-4 space-y-6 max-w-6xl">
    <!-- 商家信息展示 -->
    <div id="merchantTableContainer" class="w-full bg-white p-6 rounded shadow-md">
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-semibold">住哪儿订房</h2>
            <div class="space-x-4">

                <!-- 登录注册按钮 -->
                <button id="authButton" class="bg-purple-500 text-white px-3 py-1 rounded">切换账号</button>

                <!-- 刷新按钮 -->
                <button id="refreshButton" class="bg-blue-600 text-white px-3 py-1 rounded">刷新</button>

                <!-- 返回默认页面按钮 -->
                <button id="backToDefault" class="bg-blue-500 text-white px-3 py-1 rounded">返回默认</button>

                <!-- 搜索框 -->
                <input id="searchKeyword" type="text" placeholder="输入关键词" class="border p-1 rounded" />

                <!-- 搜索类型 -->
                <select id="searchType" class="border p-1 rounded">
                    <option value="">全部搜索</option>
                    <option value="name">按名称搜索</option>
                    <option value="keyword">按关键字搜索</option>
                </select>

                <!-- 排序字段 -->
                <select id="sortField" class="border p-1 rounded">
                    <option value="establishmentYear">按建立年份</option>
                    <option value="salesVolume">按销量</option>
                </select>

                <!-- 排序方式 -->
                <select id="sortOrder" class="border p-1 rounded">
                    <option value="asc">升序</option>
                    <option value="desc">降序</option>
                </select>

                <!-- 搜索按钮 -->
                <button id="searchButton" class="bg-green-500 text-white px-3 py-1 rounded">搜索</button>
                <!-- 重置按钮 -->
                <button id="resetButton" class="bg-gray-500 text-white px-3 py-1 rounded">重置</button>
            </div>
        </div>

        <!-- 表格内容 -->
        <div id="merchantContent">
            <p class="text-gray-500">正在加载商家信息...</p>
        </div>

        <!-- 房型信息展示 -->
        <div id="roomTypeInfoContainer" class="w-full bg-white p-6 rounded shadow-md mt-6">
            <h2 class="text-xl font-semibold">房型信息</h2>
            <div id="roomTypeInfoContent">
                <p class="text-gray-500">请点击查看商家以显示房型信息</p>
            </div>
        </div>

        <!-- 分页控件 -->
        <div id="pagination" class="flex justify-center mt-4 space-x-2"></div>
    </div>
</div>

<!-- 日期选择模态框 -->
<div id="dateModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h2>选择订房日期</h2>
        <input type="date" id="checkInDate" min="">
        <input type="date" id="checkOutDate" min="">
        <button id="confirmDate" class="bg-green-500 text-white px-3 py-1 rounded">确认</button>
    </div>
</div>


<!-- 确认订房模态框 -->
<div id="confirmModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h2>确认订房</h2>
        <p>您确定要预订该房间吗？</p>
        <button id="confirmBooking" class="bg-green-500 text-white px-3 py-1 rounded">确认</button>
        <button id="cancelBooking" class="bg-gray-500 text-white px-3 py-1 rounded">取消</button>
    </div>
</div>
<!-- 收藏原因模态框 -->
<div id="favoriteModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h2>收藏商家</h2>
        <p>请输入收藏原因：</p>
        <textarea id="favoriteReason" rows="4" cols="50" required></textarea>
        <div class="error-message" id="reasonError" style="color: red; display: none;">
            收藏原因不能为空
        </div>
        <button id="submitFavorite" class="bg-green-500 text-white px-3 py-1 rounded">提交</button>
        <button id="cancelFavorite" class="bg-gray-500 text-white px-3 py-1 rounded">取消</button>
    </div>
</div>
<!-- 收藏商家列表 -->
<div id="userFavoritesContainer" class="w-full bg-white p-6 rounded shadow-md mt-6">
    <h2 class="text-xl font-semibold flex items-center">
        <i class="fa fa-heart text-red-500 mr-2"></i>
        我的收藏
        <button id="refreshFavorites" class="ml-4 text-sm bg-blue-500 text-white px-2 py-1 rounded">
            <i class="fa fa-refresh mr-1"></i>刷新
        </button>
    </h2>
    <div id="favoritesContent">
        <p class="text-gray-500">暂无收藏商家，请点击商家后的"收藏"按钮添加</p>
    </div>
</div>
<!-- 拉黑原因模态框 -->
<div id="blockModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h2>拉黑商家</h2>
        <p>请输入拉黑原因：</p>
        <textarea id="blockReason" rows="4" cols="50" required></textarea>
        <div class="error-message" id="blockReasonError" style="color: red; display: none;">
            拉黑原因不能为空
        </div>
        <button id="submitBlock" class="bg-red-500 text-white px-3 py-1 rounded">提交</button>
        <button id="cancelBlock" class="bg-gray-500 text-white px-3 py-1 rounded">取消</button>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        const urlParams = new URLSearchParams(window.location.search);
        const username = urlParams.get('username');
        if (username) {
            document.getElementById("loggedInUser").textContent = username;
        } else {
            document.getElementById("loggedInUser").textContent = "当前用户信息获取失败";
        }
    });

    let merchantsData = [];
    let currentPage = 1;
    let pageSize = 5; // 每页显示 5 个商家
    let selectedRoomTypeId;
    let selectedRoomPrice;

    function getRefreshedUrl(url) {
        const timestamp = new Date().getTime();
        return url + (url.includes('?') ? '&' : '?') + 't=' + timestamp;
    }

    async function loadApprovedMerchants(
        keyword = '',
        searchType = '', // 区分搜索类型
        sortField = 'establishmentYear',
        sortOrder = 'asc',
        pageNumber = 1,
        pageSize = 5
    ) {
        try {
        const username = document.getElementById('loggedInUser').textContent;

        // 获取用户ID
        let userId = null;
        if (username && username !== "当前用户信息获取失败") {
            const userResponse = await fetch(`/getUserInfo?username=${encodeURIComponent(username)}`);
            if (!userResponse.ok) throw new Error(`获取用户信息失败: ${userResponse.status}`);
            const userData = await userResponse.json();
            userId = userData.userId;
        }

            let url = '/approved-merchants';
            const params = {
                keyword,
                searchType,
                sortField,
                sortOrder,
                pageNumber,
                pageSize,
                userId
            };
            const queryString = new URLSearchParams(params).toString();
            url += '?' + queryString;

            const response = await fetch(url);
            if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);

            const data = await response.json();

            const container = document.getElementById('merchantContent');
            if (data.data.length === 0) {
                container.innerHTML = '<p class="text-center text-gray-500">暂无符合条件的商家</p>';
                return;
            }

            let html = `
              <table class="min-w-full table-auto border-collapse">
                <thead>
                  <tr class="bg-gray-100 text-left">
                    <th class="py-2 px-4 border-b">商家名称</th>
                    <th class="py-2 px-4 border-b">地址</th>
                    <th class="py-2 px-4 border-b">建立年份</th>
                    <th class="py-2 px-4 border-b">联系方式</th>
                    <th class="py-2 px-4 border-b">关键字</th>
                    <th class="py-2 px-4 border-b">营业状态</th>
                    <th class="py-2 px-4 border-b">销量</th>
                    <th class="py-2 px-4 border-b">收藏量</th>
                    <th class="py-2 px-4 border-b">操作</th>
                  </tr>
                </thead>
                <tbody>`;

            data.data.forEach(m => {
                html += `
                  <tr class="hover:bg-gray-50">
                    <td class="py-2 px-4 border-b">${m.merchantName}</td>
                    <td class="py-2 px-4 border-b">${m.address || '-'}</td>
                    <td class="py-2 px-4 border-b">${m.establishmentYear || '-'}</td>
                    <td class="py-2 px-4 border-b">${m.contactInfo}</td>
                    <td class="py-2 px-4 border-b">${m.keywords}</td>
                    <td class="py-2 px-4 border-b">${m.businessStatus}</td>
                    <td class="py-2 px-4 border-b">${m.salesVolume || '-'}</td>
                    <td class="py-2 px-4 border-b">${m.favoritesCount || '-'}</td>
                    <td class="py-2 px-4 border-b">
                      <button onclick="viewMerchant('${m.merchantName}', '${m.contactInfo}', ${m.merchantId})">查看</button>
                       <button onclick="favoriteMerchant('${m.id}', '${m.merchantName}')">收藏</button>
                      <button onclick="blockMerchant('${m.id}', '${m.merchantName}')">拉黑</button>
                    </td>
                  </tr>`;
            });

            html += '</tbody></table>';
            container.innerHTML = html;

            updatePagination(data.totalItems, data.currentPage || pageNumber, data.pageSize || pageSize);

        } catch (error) {
            console.error('加载商家信息失败:', error);
            document.getElementById('merchantContent').innerHTML =
                `<p class="text-red-500">错误: ${error.message}</p>`;
        }
    }

    function updatePagination(totalItems, currentPage, pageSize) {
        const totalPages = Math.ceil(totalItems / pageSize);

        const paginationContainer = document.getElementById('pagination');
        paginationContainer.innerHTML = '';

        if (totalPages <= 1) return;

        for (let i = 1; i <= totalPages; i++) {
            const button = document.createElement('button');
            button.textContent = `第${i}页`;
            button.className = 'mx-1 px-2 py-1 bg-gray-200 rounded hover:bg-gray-300';
            if (i === currentPage) {
                button.classList.add('bg-blue-500', 'text-white');
            }

            button.addEventListener('click', () => {
                const keyword = document.getElementById('searchKeyword').value;
                const searchType = document.getElementById('searchType').value;
                const sortField = document.getElementById('sortField').value;
                const sortOrder = document.getElementById('sortOrder').value;
                loadApprovedMerchants(keyword, searchType, sortField, sortOrder, i, pageSize);
            });

            paginationContainer.appendChild(button);
        }

        const gotoInput = document.createElement('input');
        gotoInput.type = 'number';
        gotoInput.placeholder = '页码';
        gotoInput.className = 'border p-1 rounded';

        const gotoButton = document.createElement('button');
        gotoButton.textContent = '跳转';
        gotoButton.className = 'bg-green-500 text-white px-2 py-1 rounded ml-2';

        gotoButton.onclick = () => {
            const page = parseInt(gotoInput.value);
            if (page >= 1 && page <= totalPages) {
                const keyword = document.getElementById('searchKeyword').value;
                const searchType = document.getElementById('searchType').value;
                const sortField = document.getElementById('sortField').value;
                const sortOrder = document.getElementById('sortOrder').value;
                loadApprovedMerchants(keyword, searchType, sortField, sortOrder, page, pageSize);
            } else {
                alert('请输入有效页码');
            }
        };

        paginationContainer.appendChild(gotoInput);
        paginationContainer.appendChild(gotoButton);

        // 显示当前页码
        const currentPageDisplay = document.createElement('span');
        currentPageDisplay.textContent = ` 当前页码: ${currentPage} / ${totalPages}`;
        currentPageDisplay.classList.add('ml-2', 'text-gray-600');

        paginationContainer.appendChild(currentPageDisplay);
    }

    // 绑定搜索事件
    document.getElementById('searchButton').addEventListener('click', () => {
        const keyword = document.getElementById('searchKeyword').value;
        const searchType = document.getElementById('searchType').value;
        const sortField = document.getElementById('sortField').value;
        const sortOrder = document.getElementById('sortOrder').value;
        loadApprovedMerchants(keyword, searchType, sortField, sortOrder, 1, pageSize);
    });

    // 绑定重置事件
    document.getElementById('resetButton').addEventListener('click', () => {
        document.getElementById('searchKeyword').value = '';
        document.getElementById('searchType').value = '';
        document.getElementById('sortField').value = 'establishmentYear';
        document.getElementById('sortOrder').value = 'asc';
        currentPage = 1;
        loadApprovedMerchants('', '', 'establishmentYear', 'asc', 1, pageSize);
    });

    // 绑定返回默认页面事件
    document.getElementById('backToDefault').addEventListener('click', () => {
        document.getElementById('searchKeyword').value = '';
        document.getElementById('searchType').value = '';
        document.getElementById('sortField').value = 'establishmentYear';
        document.getElementById('sortOrder').value = 'asc';
        currentPage = 1;
        loadApprovedMerchants('', '', 'establishmentYear', 'asc', 1, pageSize);
    });

    // 绑定登录注册按钮事件
    document.getElementById('authButton').addEventListener('click', () => {
        window.location.href = 'auth.html';
    });

    // 绑定刷新事件
    document.getElementById('refreshButton').addEventListener('click', () => {
        const keyword = document.getElementById('searchKeyword').value;
        const searchType = document.getElementById('searchType').value;
        const sortField = document.getElementById('sortField').value;
        const sortOrder = document.getElementById('sortOrder').value;
        // 显示刷新提示
        showRefreshNotification();

        loadApprovedMerchants(keyword, searchType, sortField, sortOrder, currentPage, pageSize);
    });

    // 添加刷新提示函数
    function showRefreshNotification() {
        const notification = document.createElement('div');
        notification.textContent = '🔄 正在刷新...';
        notification.id = 'refreshNotification';
        notification.style.position = 'fixed';
        notification.style.top = '20px';
        notification.style.right = '20px';
        notification.style.backgroundColor = '#4CAF50';
        notification.style.color = 'white';
        notification.style.padding = '10px 20px';
        notification.style.borderRadius = '8px';
        notification.style.zIndex = '1000';
        notification.style.transition = 'opacity 0.5s ease-out';

        document.body.appendChild(notification);

        // 切换文本并淡出
        setTimeout(() => {
            notification.textContent = '✅ 刷新成功！';
        }, 300);

        setTimeout(() => {
            notification.style.opacity = '0';
        }, 1500);

        setTimeout(() => {
            document.body.removeChild(notification);
        }, 2000);
    }

    // 查看商家函数
async function viewMerchant(merchantName, contactInfo, merchantId) {
    console.log('查看商家参数:', { merchantName, contactInfo, merchantId }); // 打印到浏览器控制台
    const username = document.getElementById('loggedInUser').textContent;

    try {
        const userResponse = await fetch(`/getUserInfo?username=${encodeURIComponent(username)}`);
        if (!userResponse.ok) throw new Error(`HTTP 错误: ${userResponse.status}`);
        const userData = await userResponse.json();

        const userId = userData.userId;
        console.log('用户ID获取结果:', { userId }); // 打印到浏览器控制台

         // 检查商家是否已被拉黑
            if (userId) {
                const blacklistResponse = await fetch(`/check-blacklist?userId=${userId}&merchantName=${encodeURIComponent(merchantName)}`);
                if (!blacklistResponse.ok) throw new Error(`HTTP 错误: ${blacklistResponse.status}`);
                const isBlacklisted = await blacklistResponse.json();

                if (isBlacklisted) {
                    alert('该商家已被您拉黑，无法查看详情');
                    return;
                }
            }

            // 继续正常查看商家信息
        if (userId && merchantId) {
            // ✅ 确保 merchantId 和 userId 都是有效数字再传给后端
            const url = `/room-type-info?merchantName=${encodeURIComponent(merchantName)}&merchantId=${merchantId}&userId=${userId}`;
            const response = await fetch(url);
            if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);

            const data = await response.json();
            const container = document.getElementById('roomTypeInfoContent');
            if (data.length === 0) {
                container.innerHTML = '<p class="text-center text-gray-500">暂无该商家的房型信息</p>';
                return;
            }

            let html = `
              <table class="min-w-full table-auto border-collapse">
                <thead>
                  <tr class="bg-gray-100 text-left">
                    <th class="py-2 px-4 border-b">床型</th>
                    <th class="py-2 px-4 border-b">剩余数量</th>
                    <th class="py-2 px-4 border-b">关键字</th>
                    <th class="py-2 px-4 border-b">价格</th>
                    <th class="py-2 px-4 border-b">销量</th>
                    <th class="py-2 px-4 border-b">操作</th>
                  </tr>
                </thead>
                <tbody>`;

            data.forEach(roomType => {
                html += `
                  <tr class="hover:bg-gray-50">
                    <td class="py-2 px-4 border-b">${roomType.bedType}</td>
                    <td class="py-2 px-4 border-b">${roomType.remainingQuantity}</td>
                    <td class="py-2 px-4 border-b">${roomType.keywords}</td>
                    <td class="py-2 px-4 border-b">${roomType.price}</td>
                    <td class="py-2 px-4 border-b">${roomType.salesVolume}</td>
                    <td class="py-2 px-4 border-b">
                      <button onclick="bookRoom(${roomType.roomTypeId}, '${roomType.price}', '${roomType.roomTypeName}', '${roomType.bedType}', '${merchantName}', '${contactInfo}', '${merchantId}')">订房</button>
                    </td>
                  </tr>`;
            });

            html += '</tbody></table>';
            container.innerHTML = html;
        } else {
            alert('用户ID或商家ID无效，浏览记录不会被保存');
            const fallbackResponse = await fetch(`/room-type-info?merchantName=${encodeURIComponent(merchantName)}`);
            const fallbackData = await fallbackResponse.json();
            // 显示房型信息但不记录浏览历史
        }
    } catch (error) {
        console.error('加载房型信息失败:', error);
        document.getElementById('roomTypeInfoContent').innerHTML =
            `<p class="text-red-500">错误: ${error.message}</p>`;
    }
}


    // 订房函数
function bookRoom(roomTypeId, price, roomTypeName, bedType, merchantName, contactPhone) {
    selectedRoomTypeId = roomTypeId;
    selectedRoomPrice = price;
    selectedRoomTypeName = roomTypeName;
    selectedBedType = bedType;
    selectedMerchantName = merchantName;
    selectedContactPhone = contactPhone;
    const today = new Date().toISOString().split('T')[0];
    const checkInDateInput = document.getElementById('checkInDate');
    const checkOutDateInput = document.getElementById('checkOutDate');

    if (checkInDateInput && checkOutDateInput) {
        checkInDateInput.min = today;
        checkOutDateInput.min = today;
        const dateModal = document.getElementById('dateModal');
        dateModal.style.display = 'block';
    } else {
        console.error('Date input elements not found');
    }
}

    // 日期选择确认按钮事件
    document.getElementById('confirmDate').addEventListener('click', () => {
        const checkInDate = document.getElementById('checkInDate').value;
        const checkOutDate = document.getElementById('checkOutDate').value;
        if (checkInDate && checkOutDate) {
            if (new Date(checkInDate) > new Date(checkOutDate)) {
                alert('退房时间不能早于入住时间');
                return;
            }
            const confirmModal = document.getElementById('confirmModal');
            const dateModal = document.getElementById('dateModal');
            dateModal.style.display = 'none';
            confirmModal.style.display = 'block';
        } else {
            alert('请选择入住时间和退房时间');
        }
    });

    // 确认订房按钮事件
document.getElementById('confirmBooking').addEventListener('click', async () => {
    const checkInDate = document.getElementById('checkInDate').value;
    const checkOutDate = document.getElementById('checkOutDate').value;
    const username = document.getElementById('loggedInUser').textContent; // 获取当前用户名

    try {
        // 根据用户名获取用户信息
        const userResponse = await fetch(`/getUserInfo?username=${username}`);
        if (!userResponse.ok) throw new Error(`HTTP 错误: ${userResponse.status}`);
        const userData = await userResponse.json();

        const userId = userData.userId; // 获取用户ID

        if (userId) {
            try {
                const response = await fetch(`/check-balance?userId=${userId}&roomPrice=${selectedRoomPrice}`);
                if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
                const data = await response.json();
                if (data.success) {
                    // 余额足够，进行订房操作
                    const formData = new URLSearchParams();
                    formData.append('userId', userId);
                    formData.append('roomTypeId', selectedRoomTypeId);
                    formData.append('bookingDate', checkInDate);
                    formData.append('checkInDate', checkInDate);
                    formData.append('checkOutDate', checkOutDate);
                    formData.append('roomTypeName', selectedRoomTypeName);
                    formData.append('bedType', selectedBedType);
                    formData.append('merchantName', selectedMerchantName);
                    formData.append('contactPhone', selectedContactPhone);
                    formData.append('totalConsumption', selectedRoomPrice);

                    const bookResponse = await fetch('/book-room', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: formData.toString()
                    });
                    if (!bookResponse.ok) throw new Error(`HTTP 错误: ${bookResponse.status}`);
                    const bookData = await bookResponse.json();
                    if (bookData.success) {
                        alert('订房成功');
                    } else {
                        alert('订房失败: ' + bookData.message);
                    }
                } else {
                    alert('余额不足，无法订房');
                }
            } catch (error) {
                console.error('订房失败:', error);
                alert('订房失败: ' + error.message);
            }
        } else {
            alert('未获取到用户ID');
        }
    } catch (error) {
        console.error('获取用户信息失败:', error);
        alert('获取用户信息失败: ' + error.message);
    }

    const confirmModal = document.getElementById('confirmModal');
    confirmModal.style.display = 'none';
});

    // 取消订房按钮事件
    document.getElementById('cancelBooking').addEventListener('click', () => {
        const confirmModal = document.getElementById('confirmModal');
        confirmModal.style.display = 'none';
    });

    // 关闭模态框
    const closeButtons = document.querySelectorAll('.close');
    closeButtons.forEach(button => {
        button.addEventListener('click', () => {
            const modals = document.querySelectorAll('.modal');
            modals.forEach(modal => {
                modal.style.display = 'none';
            });
        });
    });

    let currentMerchantId = null;
let currentMerchantName = null;

    // 收藏商家函数
async function favoriteMerchant(merchantId, merchantName) {
    currentMerchantId = merchantId;
    currentMerchantName = merchantName;

    // 显示收藏原因模态框
    document.getElementById('favoriteModal').style.display = 'block';
    document.getElementById('favoriteReason').value = '';
    document.getElementById('reasonError').style.display = 'none';
}

// 提交收藏
document.getElementById('submitFavorite').addEventListener('click', async () => {
    const favoriteReason = document.getElementById('favoriteReason').value.trim();
    const username = document.getElementById('loggedInUser').textContent;

    // 前端验证
    if (!favoriteReason) {
        document.getElementById('reasonError').style.display = 'block';
        return;
    }

    try {
        // 获取用户ID
        const userResponse = await fetch(`/getUserInfo?username=${encodeURIComponent(username)}`);
        if (!userResponse.ok) throw new Error(`HTTP 错误: ${userResponse.status}`);
        const userData = await userResponse.json();

        const userId = userData.userId;
        if (!userId) {
            alert('未获取到用户ID，请重新登录');
            return;
        }

        // 发送收藏请求
        const formData = new URLSearchParams();
        formData.append('userId', userId);
        formData.append('merchantName', currentMerchantName);
        formData.append('favoriteReason', favoriteReason);

        const response = await fetch('/favorite-merchant', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: formData.toString()
        });

        if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
        const data = await response.json();

        if (data.success) {
            alert('收藏成功');
            document.getElementById('favoriteModal').style.display = 'none';

            // 更新商家收藏量
            await updateMerchantFavoritesCount(currentMerchantId, 1);

            // 刷新收藏列表和商家列表
            loadUserFavorites();
            const keyword = document.getElementById('searchKeyword').value;
            const searchType = document.getElementById('searchType').value;
            const sortField = document.getElementById('sortField').value;
            const sortOrder = document.getElementById('sortOrder').value;
            loadApprovedMerchants(keyword, searchType, sortField, sortOrder, currentPage, pageSize);
        } else {
            alert('收藏失败: ' + data.message);
        }
    } catch (error) {
        console.error('收藏失败:', error);
        alert('收藏失败: ' + error.message);
    }
});

    // 取消收藏
    document.getElementById('cancelFavorite').addEventListener('click', () => {
        document.getElementById('favoriteModal').style.display = 'none';
    });

    // 拉黑商家函数
    async function blockMerchant(merchantId, merchantName) {
        currentMerchantId = merchantId;
        currentMerchantName = merchantName;
        // 创建或显示拉黑原因模态框
        showBlockModal(merchantId, merchantName);
    }

    // 显示拉黑原因模态框
    function showBlockModal(merchantId, merchantName) {
        currentMerchantId = merchantId;
        currentMerchantName = merchantName;
        // 如果模态框不存在，则创建它
        if (!document.getElementById('blockModal')) {
            const modalHTML = `
            <div id="blockModal" class="modal">
                <div class="modal-content">
                    <span class="close">&times;</span>
                    <h2>拉黑商家</h2>
                    <p>请输入拉黑原因：</p>
                    <textarea id="blockReason" rows="4" cols="50" required></textarea>
                    <div class="error-message" id="blockReasonError" style="color: red; display: none;">
                        拉黑原因不能为空
                    </div>
                    <button id="submitBlock" class="bg-red-500 text-white px-3 py-1 rounded">提交</button>
                    <button id="cancelBlock" class="bg-gray-500 text-white px-3 py-1 rounded">取消</button>
                </div>
            </div>`;
            document.body.insertAdjacentHTML('beforeend', modalHTML);
        }
        // 显示模态框
        document.getElementById('blockModal').style.display = 'block';
        document.getElementById('blockReason').value = '';
        document.getElementById('blockReasonError').style.display = 'none';

        // 绑定关闭按钮事件
        document.querySelector('#blockModal .close').addEventListener('click', () => {
            document.getElementById('blockModal').style.display = 'none';
        });

        // 绑定取消按钮事件
        document.getElementById('cancelBlock').addEventListener('click', () => {
            document.getElementById('blockModal').style.display = 'none';
        });

        // 绑定提交按钮事件
        document.getElementById('submitBlock').addEventListener('click', submitBlockMerchant);
    }

    // 提交拉黑商家
    async function submitBlockMerchant() {
        const blockReason = document.getElementById('blockReason').value.trim();
        const username = document.getElementById('loggedInUser').textContent;
        // 前端验证
        if (!blockReason) {
            document.getElementById('blockReasonError').style.display = 'block';
            return;
        }
        try {
            // 获取用户ID
            const userResponse = await fetch(`/getUserInfo?username=${encodeURIComponent(username)}`);
            if (!userResponse.ok) throw new Error(`HTTP 错误: ${userResponse.status}`);
            const userData = await userResponse.json();
            const userId = userData.userId;
            if (!userId) {
                alert('未获取到用户ID，请重新登录');
                return;
            }
            // 使用fetch发送拉黑请求
            const formData = new URLSearchParams();
            formData.append('userId', userId);
            formData.append('merchantName', currentMerchantName);
            formData.append('reason', blockReason);
            const response = await fetch('/blacklist', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: formData.toString()
            });
            if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
            const data = await response.json();
            if (data.success) {
                alert('拉黑成功');
                document.getElementById('blockModal').style.display = 'none';
                // 刷新商家列表，排除已拉黑的商家
                const keyword = document.getElementById('searchKeyword').value;
                const searchType = document.getElementById('searchType').value;
                const sortField = document.getElementById('sortField').value;
                const sortOrder = document.getElementById('sortOrder').value;
                loadApprovedMerchants(keyword, searchType, sortField, sortOrder, currentPage, pageSize);
            } else {
                alert('拉黑失败: ' + data.message);
            }
        } catch (error) {
            console.error('拉黑失败:', error);
            alert('拉黑失败: ' + error.message);
        }
    }

    // 页面加载时默认请求
    window.onload = () => {
        loadApprovedMerchants();
    };

    // 获取并显示用户收藏
async function loadUserFavorites() {
    const username = document.getElementById('loggedInUser').textContent;
    if (!username || username === "当前用户信息获取失败") {
        document.getElementById('favoritesContent').innerHTML =
            '<p class="text-red-500">请先登录以查看收藏</p>';
        return;
    }

    try {
        // 获取用户ID
        const userResponse = await fetch(`/getUserInfo?username=${encodeURIComponent(username)}`);
        if (!userResponse.ok) throw new Error(`HTTP 错误: ${userResponse.status}`);
        const userData = await userResponse.json();

        const userId = userData.userId;
        if (!userId) {
            document.getElementById('favoritesContent').innerHTML =
                '<p class="text-red-500">无法获取用户ID，请重新登录</p>';
            return;
        }

        // 获取收藏列表
        const favoritesResponse = await fetch(`/user-favorites?userId=${userId}`);
        if (!favoritesResponse.ok) throw new Error(`HTTP 错误: ${favoritesResponse.status}`);
        const favoritesData = await favoritesResponse.json();

        const container = document.getElementById('favoritesContent');

        if (!favoritesData.success || favoritesData.data.length === 0) {
            container.innerHTML = '<p class="text-gray-500">暂无收藏商家，请点击商家后的"收藏"按钮添加</p>';
            return;
        }

        let html = `
            <table class="min-w-full table-auto border-collapse">
                <thead>
                    <tr class="bg-gray-100 text-left">
                        <th class="py-2 px-4 border-b">商家名称</th>
                        <th class="py-2 px-4 border-b">收藏原因</th>
                        <th class="py-2 px-4 border-b">收藏时间</th>
                        <th class="py-2 px-4 border-b">操作</th>
                    </tr>
                </thead>
                <tbody>`;

        favoritesData.data.forEach(favorite => {
            html += `
                <tr class="hover:bg-gray-50">
                    <td class="py-2 px-4 border-b">${favorite.merchantName}</td>
                    <td class="py-2 px-4 border-b">${favorite.favoriteReason}</td>
                    <td class="py-2 px-4 border-b">${formatDateTime(favorite.favoriteTime)}</td>
                    <td class="py-2 px-4 border-b">
                        <button onclick="unfavoriteMerchant(${favorite.favoriteId}, '${favorite.merchantName}')">
                            取消收藏
                        </button>
                    </td>
                </tr>`;
        });

        html += `</tbody></table>`;
        container.innerHTML = html;

    } catch (error) {
        console.error('加载收藏列表失败:', error);
        document.getElementById('favoritesContent').innerHTML =
            `<p class="text-red-500">错误: ${error.message}</p>`;
    }
}

// 格式化日期时间
function formatDateTime(dateTimeString) {
    if (!dateTimeString) return '';
    const date = new Date(dateTimeString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 取消收藏
async function unfavoriteMerchant(favoriteId, merchantName) {
    if (!confirm(`确定要取消收藏"${merchantName}"吗？`)) {
        return;
    }

    try {
        const response = await fetch(`/unfavorite?favoriteId=${favoriteId}`, {
            method: 'DELETE'
        });

        if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
        const data = await response.json();

        if (data.success) {
            alert('取消收藏成功');

            // 获取商家ID
            const merchantId = await getMerchantIdByName(merchantName);
            if (merchantId) {
                // 更新商家收藏量
                await updateMerchantFavoritesCount(merchantId, -1);
            }

            loadUserFavorites(); // 刷新收藏列表
            // 刷新商家列表，更新收藏数量
            const keyword = document.getElementById('searchKeyword').value;
            const searchType = document.getElementById('searchType').value;
            const sortField = document.getElementById('sortField').value;
            const sortOrder = document.getElementById('sortOrder').value;
            loadApprovedMerchants(keyword, searchType, sortField, sortOrder, currentPage, pageSize);
        } else {
            alert('取消收藏失败: ' + data.message);
        }
    } catch (error) {
        console.error('取消收藏失败:', error);
        alert('取消收藏失败: ' + error.message);
    }
}

    // 绑定刷新收藏按钮事件
    document.getElementById('refreshFavorites').addEventListener('click', loadUserFavorites);

    // 页面加载时加载收藏列表
    window.onload = () => {
    loadApprovedMerchants();
    loadUserFavorites(); // 新增加载收藏列表
};

    // 更新商家收藏量的函数
async function updateMerchantFavoritesCount(merchantId, change) {
    try {
        const response = await fetch(`/update-favorites-count?merchantId=${merchantId}&change=${change}`, {
            method: 'POST'
        });
        if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
    } catch (error) {
        console.error('更新收藏量失败:', error);
    }
}

    // 根据商家名称获取商家ID的函数
async function getMerchantIdByName(merchantName) {
    try {
        const response = await fetch(`/get-merchant-id?merchantName=${encodeURIComponent(merchantName)}`);
        if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
        const data = await response.json();
        return data.merchantId;
    } catch (error) {
        console.error('获取商家ID失败:', error);
        return null;
    }
}
</script>
</body>
</html>